package edu.hawaii.duedates.libraries;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

import edu.hawaii.duedates.Book;
import edu.hawaii.duedates.Library;
import edu.hawaii.duedates.LibraryUser;

/**
 * UHMLibrary.class
 * UHMLibrary enables the communication between our DueDates interface and the 
 * physical UHM Library System. It is also responsible for retrieving the 
 * required information, given the parameters passed by DueDates.
 *  
 * @author Anthony Du, Vincent Leung 
 *
 */
public class UHMLibrary extends Library {
    // Library name
    private static String UHM_NAME = "University of Hawaii at Manoa Library";
    
  /**
   * Constructor for creating a library and setting user's credentials.
   */
  public UHMLibrary() {
    this.setLibName(UHM_NAME);
  }
  
  /**
   * Attempts to login to UH Manoa Library system.  
   * @param user LibraryUser object. 
   * @return The WebConversation instance after successful login. 
   * @throws Exception If login was not successful with these credentials. 
   */
  @Override
  public WebConversation logIntoLibrary(LibraryUser user) throws Exception {
    String url = "http://uhmanoa.lib.hawaii.edu/cgi-bin/Pwebrecon.cgi?DB=local&PAGE=pbLogon";
    // UH Library website has bogus JavaScript code.
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);
    // create the conversation object which will maintain state for us
    WebConversation conversation = new WebConversation();
    WebRequest request = new GetMethodWebRequest(url);
    WebResponse response = conversation.getResponse(request);
    WebForm form = response.getFormWithName("logonpage");
    form.setParameter("BC", user.getId());
    form.setParameter("LN", user.getPassword());
    form.submit();
    response = conversation.getCurrentPage();
    if (response.getText().contains("Sorry, Login unsuccessful")) {
      System.out.println("Sorry, Login unsuccessful.");
      throw new Exception("Error while logging in to UH Library");
    }
    return conversation;
  }
  
  /**
   * Given a logged in user to the UH Library site, provides info about their library books.
   * @param user LibraryUser object. 
   * @return String containing user requested info.
   * @throws Exception if problems occur parsing the site pages. 
   */
  @Override
  public String getLibInfo(LibraryUser user) throws Exception {
    String dateFormat = "MM-dd-yy";
    SimpleDateFormat formattedDate = new SimpleDateFormat(dateFormat, Locale.US);
    
    try {
      WebConversation conversation = logIntoLibrary(user);
      WebResponse response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];
      String uhSiteNoItemString = "You have no items checked out.";
      if (uhSiteNoItemString.equals(form.getText())) {
        return "No books checked out";
      }
      else {
        WebTable table = response.getTableStartingWith("Status");
      
        // if the user did not borrow anything from the library
        if (table == null) {
          return "No books checked out";
        }

        for (int i = 1; i <= table.getRowCount() - 1; i++) {
          String dueDate = table.getCellAsText(i, table.getColumnCount() - 1);
          if (dueDate.length() >= 8) {
            dueDate = dueDate.substring(dueDate.length() - 8);
          }
          // Book's information (title, author, etc.).
          String bookInfo = table.getCellAsText(i, 1);
          // Book's status/due date.
          Date duedate = formattedDate.parse(dueDate);
          // Add new book to list of library books.
          this.addBook(new Book(bookInfo, duedate));
        }
        return null;
      }
    }
    catch (Exception e) {
      throw new Exception("Unable to get UH Book info:\n  " + e.getMessage(), e);
    }
  }
}